<script setup>
import { ref } from 'vue'
import { saveUserSafe } from '@/api/user'
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user'

// 获取登录用户信息
const userStore = useUserStore();
console.log(userStore.id);

// 表单数据
const form = ref({
    userid: userStore.id,
    password: '',
    newpassword: '',
    confirm_password: ''
})

// 表单校验
const rules = ref({
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    newpassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
    confirm_password: [{ required: true, message: '请再次输入新密码', trigger: 'blur' }]
});


/** 保存按钮 */
function submit() {
    if (!form.value.password) {
        ElMessage.error('请输入原密码')
    } else if (!form.value.newpassword || !form.value.confirm_password) {
        ElMessage.error('请输入新密码')
        return
    } else if (form.value.newpassword != form.value.confirm_password) {
        ElMessage.error('两次输入密码不一致')
        return
    } else {
        saveUserSafe(form.value).then(res=>{
            if(res.code==200){
                ElMessage.success('修改成功')
            }
        })
        .catch(err=>{
            console.log(err);
            ElMessage.error('保存失败，请重试')
        })
    }
}

</script>

<template>
    <h2 style="padding-left: 30px;">安全设置</h2>
    <hr style="margin-bottom: 20px;">
    <div class="user-center">
        <el-form ref="userRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="原密码" prop="password">
                <el-input v-model="form.password" maxlength="30" />
            </el-form-item>
            <el-form-item label="新密码" prop="newpassword">
                <el-input v-model="form.newpassword" maxlength="11" />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirm_password">
                <el-input v-model="form.confirm_password" maxlength="50" />
            </el-form-item>
            <el-form-item>
            <el-button type="primary" @click="submit">保存</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<style scoped lang="scss">
.user-center{
    width: 600px;
    margin-left: 80px;
}

</style>